import React, { useState } from 'react'
import { PageContainer, ProTable } from '@ant-design/pro-components'
import { Tabs, Button, Tag, Space, Modal, Form, Input, Switch, message } from 'antd'
import { getJobList, addJob, editJob, deleteJob } from '@/services/ai';


const SettingsPage: React.FC = () => {
  const tabList = [{ name: '配置联网', value: 1 }, { name: '配置深度思考', value: 2 }]
  const [addModalVisible, setAddModalVisible] = useState(false)
  const [editModalVisible, setEditModalVisible] = useState(false)
  const [form] = Form.useForm()
  const [refreshKey, setRefreshKey] = useState(0)
  const [activeTab, setActiveTab] = useState<string>('1')
  const [editingRecord, setEditingRecord] = useState<any>(null)
  const [tableLoading, setTableLoading] = useState(false)

  // 添加数据的方法
  const addData = () => {
    setAddModalVisible(true)
  }

  // 处理添加数据提交
  const handleAddSubmit = async (values: any) => {
    try {
      const data = {
        type: parseInt(activeTab), // 使用当前选中的tab类型
        params: values.params || '', // 职位/参数
        value: values.enableDeepThinking ? 1 : 2// 是否开启
      }

      await addJob(data)
      message.success('添加成功')
      setAddModalVisible(false)
      form.resetFields()
      // 触发表格刷新
      setRefreshKey(prev => prev + 1)
    } catch (error) {
      console.error('添加失败:', error)
      message.error('添加失败，请重试')
    }
  }

  // 取消添加
  const handleAddCancel = () => {
    setAddModalVisible(false)
    form.resetFields()
  }

  // 编辑数据的方法
  const handleEdit = (record: any) => {
    setEditingRecord(record)
    form.setFieldsValue({
      params: record.params,
      enableDeepThinking: record.value === 1 || record.value === '1'
    })
    setEditModalVisible(true)
  }

  // 处理编辑数据提交
  const handleEditSubmit = async (values: any) => {
    try {
      const data = {
        id: editingRecord.id,
        type: editingRecord.type,
        params: values.params || '',
        value: values.enableDeepThinking ? 1 : 2
      }

      await editJob(data)
      message.success('编辑成功')
      setEditModalVisible(false)
      form.resetFields()
      setEditingRecord(null)
      // 触发表格刷新
      setRefreshKey(prev => prev + 1)
    } catch (error) {
      console.error('编辑失败:', error)
      message.error('编辑失败，请重试')
    }
  }

  // 取消编辑
  const handleEditCancel = () => {
    setEditModalVisible(false)
    form.resetFields()
    setEditingRecord(null)
  }

  // 删除数据的方法
  const handleDelete = (record: any) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除这条${activeTab === '1' ? '联网' : '深度思考'}配置吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          await deleteJob({ id: record.id })
          message.success('删除成功')
          // 触发表格刷新
          setRefreshKey(prev => prev + 1)
        } catch (error) {
          console.error('删除失败:', error)
          message.error('删除失败，请重试')
        }
      },
    })
  }

  // 处理 Tab 切换
  const handleTabChange = (newActiveKey: string) => {
    console.log('Tab切换:', newActiveKey, newActiveKey === '1' ? '联网' : '深度思考');
    setActiveTab(newActiveKey);
    // 切换 Tab 时显示 loading 并触发表格刷新
    setTableLoading(true);
    setRefreshKey(prev => prev + 1);
  };


  return (
    <PageContainer
      header={{
        title: '',
      }}
    >
      <div style={{ marginBottom: '16px' }}>
        {tabList.length > 0 && (
          <Tabs
            activeKey={activeTab}
            onChange={handleTabChange}
            items={tabList.map((item) => ({
              key: item.value.toString(),
              label: item.name,
            }))}
            type="card"
            style={{ marginBottom: '16px' }}
          />
        )}
      </div>
      <ProTable
        key={refreshKey}
        columns={[
          {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            width: 80,
            render: (_, record: any, index: number) => index + 1,
          },
          {
            title: '职位',
            dataIndex: 'params',
            key: 'params',
            ellipsis: true,
            render: (text) => text || '无',
          },
          {
            title: '是否开启',
            dataIndex: 'value',
            key: 'value',
            render: (_, record: any) => {
              const value = record.value;
              const isEnabled = value === '1';
              return (
                <Tag color={isEnabled ? 'success' : 'default'}>
                  {isEnabled ? '开启' : '关闭'}
                </Tag>
              );
            },
          },
          {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            render: (_, record: any) => {
              const text = record.createTime;
              if (!text) return '未知';
              return new Date(text).toLocaleString('zh-CN');
            },
            sorter: (a: any, b: any) => {
              if (!a.createTime || !b.createTime) return 0;
              return new Date(a.createTime).getTime() - new Date(b.createTime).getTime();
            },
          },
          {
            title: '更新时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
            render: (_, record: any) => {
              const text = record.updateTime;
              if (!text) return '';
              return new Date(text).toLocaleString('zh-CN');
            },
            sorter: (a: any, b: any) => {
              if (!a.updateTime || !b.updateTime) return 0;
              return new Date(a.updateTime).getTime() - new Date(b.updateTime).getTime();
            },
          },
          {
            title: '操作',
            key: 'action',
            render: (_, record: any) => (
              <Space>
                <Button
                  type="link"
                  size="small"
                  onClick={() => handleEdit(record)}
                >
                  编辑
                </Button>
                <Button
                  type="link"
                  size="small"
                  danger
                  onClick={() => handleDelete(record)}
                >
                  删除
                </Button>
              </Space>
            ),
          },
        ]}
        loading={tableLoading}
        rowKey="id"
        search={false}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/总共 ${total} 条`,
        }}
        options={{
          reload: true,
          density: true,
          fullScreen: true,
          setting: true,
        }}
        toolBarRender={() => [
          <Button key="add" type="primary" onClick={addData}>
            添加
          </Button>,
        ]}
        request={async (params, sorter) => {

          try {
            setTableLoading(true);
            // 调用真实API
            const response = await getJobList(parseInt(activeTab));
            const data = response?.data.records || [];

            // 应用排序
            let sortedData = [...data];

            if (sorter.createTime) {
              sortedData.sort((a: any, b: any) => {
                const aTime = new Date(a.createTime).getTime();
                const bTime = new Date(b.createTime).getTime();
                return sorter.createTime === 'ascend' ? aTime - bTime : bTime - aTime;
              });
            } else if (sorter.updateTime) {
              sortedData.sort((a: any, b: any) => {
                const aTime = new Date(a.updateTime).getTime();
                const bTime = new Date(b.updateTime).getTime();
                return sorter.updateTime === 'ascend' ? aTime - bTime : bTime - aTime;
              });
            }

            // 应用分页
            const pageSize = params.pageSize || 10;
            const current = params.current || 1;
            const start = (current - 1) * pageSize;
            const end = start + pageSize;
            const paginatedData = sortedData.slice(start, end);

            setTableLoading(false);
            return {
              data: paginatedData,
              success: true,
              total: sortedData.length,
            };
          } catch (error) {
            setTableLoading(false);
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
      />

      {/* 添加数据弹框 */}
      <Modal
        title={`添加${activeTab === '1' ? '联网' : '深度思考'}配置`}
        open={addModalVisible}
        onOk={() => form.submit()}
        onCancel={handleAddCancel}
        okText="确定"
        cancelText="取消"
        width={500}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleAddSubmit}
        >
          <Form.Item
            name="params"
            label={'职位'}
            rules={[
              { required: true, message: `请输入${'职位'}` },
              { max: 100, message: '不能超过100个字符' }
            ]}
          >
            <Input placeholder={`请输入${'职位'}`} />
          </Form.Item>

          <Form.Item
            name="enableDeepThinking"
            label={activeTab === '1' ? '是否开启联网' : '是否开启深度思考'}
            valuePropName="checked"
            initialValue={false}
          >
            <Switch
              checkedChildren="开启"
              unCheckedChildren="关闭"
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑数据弹框 */}
      <Modal
        title={`编辑${activeTab === '1' ? '联网' : '深度思考'}配置`}
        open={editModalVisible}
        onOk={() => form.submit()}
        onCancel={handleEditCancel}
        okText="确定"
        cancelText="取消"
        width={500}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleEditSubmit}
        >
          <Form.Item
            name="params"
            label={'职位'}
            rules={[
              { required: true, message: `请输入${'职位'}` },
              { max: 100, message: '不能超过100个字符' }
            ]}
          >
            <Input placeholder={`请输入${'职位'}`} />
          </Form.Item>

          <Form.Item
            name="enableDeepThinking"
            label={activeTab === '1' ? '是否开启联网' : '是否开启深度思考'}
            valuePropName="checked"
          >
            <Switch
              checkedChildren="开启"
              unCheckedChildren="关闭"
            />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default SettingsPage;
